package com.ruoyi.common.utils.baidu;

//import org.json.JSONObject;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * token的获取类
 * 将apiKey和secretKey换取token，注意有效期保存在expiresAt
 */
@Component
@Slf4j
public class BaiduTtsTokenHolder {

    public static final String ASR_SCOPE = "audio_voice_assistant_get";

    public static final String TTS_SCOPE = "audio_tts_post";

    /**
     * URL , Token的url，http可以改为https
     */
    private static final String URL = "http://aip.baidubce.com/oauth/2.0/token";

    /**
     * asr的权限 scope 是  "audio_voice_assistant_get"
     * tts 的权限 scope 是 "audio_tts_post"
     */
    private String scope;

    /**
     * 网页上申请语音识别应用获取的apiKey
     */
    @Value("${baiduTts.appKey}")
    private String apiKey;

    /**
     * 网页上申请语音识别应用获取的secretKey
     */
    @Value("${baiduTts.secretKey}")
    private String secretKey;

    /**
     * 百度地图apiKey
     */
    @Value("${baiduMap.appKey}")
    private String apiKey1;

    /**
     * 保存访问接口获取的token
     */
    private String token;

    /**
     * 当前的时间戳，毫秒
     */
    private long expiresAt;

    /**
     * 获取token，refresh 方法后调用有效
     *
     * @return
     */
    public String getToken() {
        return token;
    }

    /**
     * 获取过期时间，refresh 方法后调用有效
     *
     * @return
     */
    public long getExpiresAt() {
        return expiresAt;
    }

    @Autowired
    private BaiduMapUtils baiduMapUtils;

    /**
     * 更新百度智能云accessToken。
     * 百度智能云鉴权认证机制：https://ai.baidu.com/ai-doc/REFERENCE/Lkru0zoz4
     *
     * @return
     */
    @PostConstruct
    public String refreshBaiduTtsAccessToken() {
        String refreshTokenURL = URL + "?grant_type=client_credentials"
                + "&client_id=" + ConnUtil.urlEncode(apiKey) + "&client_secret=" + ConnUtil.urlEncode(secretKey);

        // 打印的url出来放到浏览器内可以复现
        log.info("refreshTokenURL: {}", refreshTokenURL);

//        baiduMapUtils.translateWgs84ToBd09("29.488069,118.991258,29.488613,118.990918,29.489193,118.990932,29.489963,118.99155,29.489963,118.99155");
//        baiduMapUtils.translateWgs84ToBd09("118.991258,29.488069;118.990918,29.488613");
//        Map params = new LinkedHashMap<String, String>();
////        params.put("coords", "114.21892734521,29.575429778924");
//        params.put("coords", "118.991258,29.488069;118.990918,29.488613");
////        params.put("coords", "118.991258,29.488069");
//        params.put("from", "1");
//        params.put("to", "5");
//        params.put("ak", apiKey1);
//        baiduMapUtils.requestGetAK(params);

        try {
            URL urlconn = new URL(refreshTokenURL);
            HttpURLConnection conn = (HttpURLConnection) urlconn.openConnection();
            conn.setConnectTimeout(5000);
            String result = ConnUtil.getResponseString(conn);
            log.info("baiduTtsAccessToken result json: {}", result);
//            parseJson(result);
            JSONObject json = JSONObject.parseObject(result);
            token = json.getString("access_token");
            expiresAt = System.currentTimeMillis() + json.getLong("expires_in") * 1000;

            return token;
        } catch (IOException e) {
//            throw new RuntimeException(e);
            log.error("更新百度智能云accessToken失败，error: {}", e.getMessage());
        }

        return null;
    }

    /**
     * @param result token接口获得的result
     */
    private void parseJson(String result) {
        JSONObject json = JSONObject.parseObject(result);
//        if (!json.has("access_token")) {
//            // 返回没有access_token字段
//            throw new DemoException("access_token not obtained, " + result);
//        }
//        if (!json.has("scope")) {
//            // 返回没有scope字段
//            throw new DemoException("scope not obtained, " + result);
//        }
//        if (!json.getString("scope").contains(scope)) {
//            throw new DemoException("scope not exist, " + scope + "," + result);
//        }
        token = json.getString("access_token");
        expiresAt = System.currentTimeMillis() + json.getLong("expires_in") * 1000;
    }
}